package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.AbnormalListAdapter;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.bean.DNReform;
import com.example.administrator.yanfoxconn.bean.DNSpinner;
import com.example.administrator.yanfoxconn.bean.DimemsionMenu;
import com.example.administrator.yanfoxconn.bean.RouteMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.example.administrator.yanfoxconn.widget.SwipeListViewOne;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Song
 * on 2021/7/10
 * Description：宿舍巡检維護 异常整改列表界面
 */
public class BGReformListActivity extends BaseActivity implements View.OnClickListener , AdapterView.OnItemClickListener {
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息回復
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_BUILDING = 6;//棟
    private final int MESSAGE_SET_FLOOR = 7;//層
    private final int MESSAGE_SET_ROOM = 8;//房間
    private final int MESSAGE_SEE_ABNORMAL = 4;

    private String[] areaSource = {"A區", "C區", "幹部樓", "E區", "D區","吸煙區"};
    public String[] bgGroupType = {"BL", "BM", "BO", "BN", "BQ","KE"};
    private String area = "";    //區域
    private String building = "";//樓棟
    private String floor = "";   //樓層
    private List<String> areaData = new ArrayList<>();//區域列表
    private List<String> buildingData = new ArrayList<>();//樓棟列表
    private List<String> floorData = new ArrayList<>();//樓層列表
    private String url,type;//請求地址
    private String result;//返回結果
    private List<DimemsionMenu> dimemsionMenuList,floorList;//宿舍棟菜單

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.ll_tr)
    LinearLayout llTR;//查詢條件部分
    @BindView(R.id.sp_area)
    Spinner spArea;//區域
    @BindView(R.id.sp_building)
    Spinner spBuilding;//樓棟
    @BindView(R.id.sp_floor)
    Spinner spFloor;//樓層
    @BindView(R.id.tv_room)
    TextView tvRoom;
    @BindView(R.id.sp_room)
    Spinner spRoom;//房間
    @BindView(R.id.btn_check)
    Button btnCheck;//查詢
    @BindView(R.id.lv_dn_remark)
    SwipeListViewOne listViewOne;
    @BindView(R.id.lv_abnormal)
    MyListView lvAbnormal;//列表

    private DNReformAdapter dnReformAdapter;
    private List<DNReform> reformList;
    private List<DNReform> chongZuReformList;

    private AbnormalListAdapter abnormalListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dn_reform_lv);
        ButterKnife.bind(this);
        tvRoom.setVisibility(View.GONE);
        spRoom.setVisibility(View.GONE);
        listViewOne.setVisibility(View.GONE);
        lvAbnormal.setVisibility(View.VISIBLE);
        tvTitle.setText("異常整改");
        btnBack.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        lvAbnormal.setOnItemClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_check://查詢
                getList(floor);
                break;
        }
    }

    //獲取區域
    private void getArea() {
        for (int i = 0; i < areaSource.length; i++) {
            areaData.add(areaSource[i]);
        }
        setArea();
    }

    /**
     * 獲取宿舍樓棟
     */
    public void getBuilding(String type) {
        showDialog();
        url = Constants.HTTP_MENU_SERVLET + "?type=" + type;

        FoxContext.getInstance().setType(type);
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForGet(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        dimemsionMenuList = new ArrayList<DimemsionMenu>();
                        for (JsonElement type1 : array) {
                            DimemsionMenu humi = gson.fromJson(type1, DimemsionMenu.class);
                            dimemsionMenuList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_BUILDING;
                        mHandler.sendMessage(message);

                    }
                }
            }
        }.start();

    }
    /**
     * 獲取宿舍樓層
     */
    public void getFloor(String type,String build) {
        showDialog();
        url = Constants.HTTP_MENU_FLOOR_SERVLET + "?type=" + type+"&build="+build;

        FoxContext.getInstance().setType(type);
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        floorList = new ArrayList<DimemsionMenu>();
                        for (JsonElement type1 : array) {
                            DimemsionMenu humi = gson.fromJson(type1, DimemsionMenu.class);
                            floorList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_FLOOR;
                        mHandler.sendMessage(message);

                    }
                }
            }
        }.start();

    }



private String areaid="";

    public void setArea() {

        //區域下拉列表選擇
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, areaData));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                area = areaData.get(position);
                areaid = bgGroupType[position];
                FoxContext.getInstance().setType(areaid);
                type=FoxContext.getInstance().getType();
                if (area.equals(areaData.get(0))){

                }else{
                    buildingData.clear();
                }
                getBuilding(areaid);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
private String build="";
    public void setBuilding() {

if (dimemsionMenuList.size()>0){
    buildingData.add("選擇");
    for (int i = 0 ;i<dimemsionMenuList.size();i++){
    buildingData.add(dimemsionMenuList.get(i).getDim_flag_name());}
}
        //樓棟下拉列表選擇
        spBuilding.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, buildingData));
        spBuilding.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                building = buildingData.get(position);
                if (building.equals("選擇")) {
                    floorData=new ArrayList<>();
                    floorData.add("選擇");
                    setFloor();
                } else{
                    floorData.clear();
                    build=dimemsionMenuList.get(position-1).getDim_flag();
                    getFloor(areaid,build);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    public void setFloor() {
        if (floorList!=null){
            floorData.add("選擇");
            for (int i = 0;i<floorList.size();i++) {
                floorData.add(floorList.get(i).getDim_floor());
            }
        }
        //樓層下拉列表選擇
        spFloor.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, floorData));
        spFloor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                floor = floorData.get(position);

                if (floor.equals("選擇")) {
                    getList("");
                } else { getList(floor);}
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private String url2 = "";

    public void getList(String floorIsNull) {

        try {

            if (building.equals("選擇") ) {
                ToastUtils.showLong(BGReformListActivity.this, "請正確選擇區,棟的信息!");
            } else {
                String building1 = URLEncoder.encode(URLEncoder.encode(build, "UTF-8"), "UTF-8");
                String floor1 = URLEncoder.encode(URLEncoder.encode(floorIsNull, "UTF-8"), "UTF-8");
                toSeeAbnormalActivity(FoxContext.getInstance().getType(),building1,floor1);}

        Log.e("------url2------", url2);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
    /**
     * 獲取有異常的點位
     * @param flag         類別
     * @param type         權限
     * @param textDateTime 時間
     */
    private List<RouteMessage> routeMessageList;
    private void toSeeAbnormalActivity(String type, String build,String floor) {

        showDialog();
        final String url = Constants.HTTP_BGMENU_EXCE_VIEW_SERVLET + "?type=" + type + "&build=" + build + "&floor=" + floor+"&flag=D";

        Log.e("-------fff--", "url==" + url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                Log.e("--fff---result----", result.toString());
                if (result != null) {
                    routeMessageList = new ArrayList<RouteMessage>();
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray array = jsonObject.get("result").getAsJsonArray();

                        for (JsonElement type : array) {
                            RouteMessage humi = gson.fromJson(type, RouteMessage.class);
                            routeMessageList.add(humi);
                        }

                        Message message = new Message();
                        message.what = MESSAGE_SEE_ABNORMAL;
                        message.obj = routeMessageList;
                        mHandler.sendMessage(message);

                    } else if (errCode.equals("400")) {
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = "400";
                        mHandler.sendMessage(message);
                        routeMessageList.clear();

                    }
                } else {
                    ToastUtils.showShort(BGReformListActivity.this, "請求不成功");
                }

            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    if (msg.obj.equals("400")) {

                            abnormalListAdapter = new AbnormalListAdapter(BGReformListActivity.this, routeMessageList, null, "D");
                            ToastUtils.showShort(BGReformListActivity.this, "此點無異常數據!");
                        lvAbnormal.setAdapter(abnormalListAdapter);
                    } else {
                        ToastUtils.showShort(BGReformListActivity.this, msg.obj.toString());

                    }
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(BGReformListActivity.this, R.string.net_mistake);
                    break;
                case MESSAGE_SET_TEXT://進度賦值
                    break;
                case MESSAGE_SET_BUILDING://樓棟賦值
                    setBuilding();
                    break;
                case MESSAGE_SET_FLOOR://樓層賦值
                    setFloor();
                    break;
                case MESSAGE_SEE_ABNORMAL://跳轉異常列表
                        abnormalListAdapter = new AbnormalListAdapter(BGReformListActivity.this, routeMessageList, null, "D");
                        lvAbnormal.setAdapter(abnormalListAdapter);
                    break;
            }
            super.handleMessage(msg);
        }
    };



    @Override
    protected void onStart() {
        super.onStart();
        if (building.equals("") || floor.equals("")) {
            getArea();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        switch (adapterView.getId()) {
            case R.id.lv_abnormal://列表點擊事件

                    Intent intent = new Intent(BGReformListActivity.this, ComAbAbnormalListActivity.class);
                    intent.putExtra("dimId",routeMessageList.get(position).getDim_id());
                    intent.putExtra("dName",routeMessageList.get(position).getDim_locale());
                    if (type.equals("IL")||type.equals("IM")||type.equals("IN")||type.equals("IO")||type.equals("IP")||type.equals("BL")||type.equals("BM")||type.equals("BN")||type.equals("BO")||type.equals("BQ")||type.equals("KE")){
                        intent.putExtra("scId","");

                    }else{
                        intent.putExtra("scId",routeMessageList.get(position).getSc_id());
                    }
                    intent.putExtra("isDate",true);//顯示日期前後天按鈕
                    intent.putExtra("creater","");
                    startActivity(intent);
                break;
        }
    }

}